require File.dirname(__FILE__) + '/DatabaseCommunication.rb'
require File.dirname(__FILE__) + '/IRISPoller.rb'

class SFMonitor

  attr_accessor :iris, :db, :last_log, :entries

  def initialize
    @iris = IrisPoller.new
    @db = DbConnection.new
    @last_log = Time.now.hour
    @entries = @db.total_entries
    log Time.now.asctime + ": Starting up poller"
  end

  def run(interval=15)
    continue = true
    time = Time.now
    poll_cnt = 0

    while continue == true

      # determine whether to poll
      if Time.now - time > interval
        poll
        poll_cnt += 1
        time = time + 15
      else
        sleep 0.2
      end

      # determine whether to write to log
      if !(@last_log == time.hour) 
        current_entries = @db.total_entries
        log time.asctime + ": polled sensors " + poll_cnt.to_s + " times, " + (current_entries - @entries).to_s + " rows added to database."

        poll_cnt = 0
        @last_log = time.hour
        @entries = current_entries
      end

    end
  rescue Exception => e
    log Time.now.asctime + ": Exception caught: #{ e } (#{ e.class })!"
  end

  def poll
    data = @iris.poll_hosts
    data.each { |p|
      @db.add_data(p[0], p[1], p[2], p[3])
    }
  end

  def log(input, file_name=File.dirname(__FILE__) + "/../log.txt")
    if File.file?(file_name)
      log = File.new(file_name, "r+")
      log.readlines
    else
      log = File.new(file_name, "w")
      log.puts("Log file for SF Monitor:\n")
    end

    log.puts input

    log.close
  end

end

# example usage
# mon = SFMonitor.new
# mon.run
